using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class AdminPos_ProductDisplay : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadLoginInHiddenField();
            loadACC_ChartOfAccountLabel4();
            loadPos_Color();
            loadPos_Size();
            loadProductStatus();
            initialLoad();
          
        }
    }

    private void initialLoad()
    {
        //txtDate.Text = DateTime.Today.ToString("dd MMM yyyy");
        int transactionTypeID = int.Parse(Request.QueryString["TransactionTypeID"]);
        txtBackDatedSale.Text = DateTime.Today.ToString("dd MMM yyyy");
        if (transactionTypeID == 13)
        {
            UpdatePanel2.Visible = false;
            lblVoucherType.Text = "Sales";
        }
        else
        { 
        lblVoucherType.Text = "Sales Return Out";
        }
    }

    private void loadACC_ChartOfAccountLabel4()
    {
        List<ACC_ChartOfAccountLabel4> aCC_ChartOfAccountLabel4s = new List<ACC_ChartOfAccountLabel4>();
        aCC_ChartOfAccountLabel4s = ACC_ChartOfAccountLabel4Manager.GetAllACC_ChartOfAccountLabel4sForJournalEntry();

        ddlProduct.Items.Add(new ListItem("Any Product", "0"));
        ddlRefference.Items.Add(new ListItem("No Refference", "0"));
        foreach (ACC_ChartOfAccountLabel4 aCC_ChartOfAccountLabel4 in aCC_ChartOfAccountLabel4s)
        {
            ListItem item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_HeadTypeID.ToString() + "@" + aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());

            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 3)
            {
                item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                ddlProduct.Items.Add(item);
            }

            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 1)
            {
                if (aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.Contains("Show"))
                {
                    item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                    ddlWorkStationSearch.Items.Add(item);
                }
            }
            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 7) // share holder
            {
                
                    item = new ListItem("00-"+aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                ddlRefference.Items.Add(item);
            }

            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 4)
            {
                try
                {
                    if (int.Parse(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.Split('-')[0])>0)
                    {
                        item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                        ddlSalesPersonAll.Items.Add(item);
                    }
                }
                catch(Exception ex)
                {}
            }
            
        }

        foreach (ACC_ChartOfAccountLabel4 aCC_ChartOfAccountLabel4 in aCC_ChartOfAccountLabel4s)
        {
            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 4
                &&
                aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.Contains("H1")
                ) //Head Office
            {
                ListItem item = new ListItem();
                item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                ddlRefference.Items.Add(item);
            }
        }

        foreach (ACC_ChartOfAccountLabel4 aCC_ChartOfAccountLabel4 in aCC_ChartOfAccountLabel4s)
        {
            if (aCC_ChartOfAccountLabel4.ACC_HeadTypeID == 4
                &&
                !aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.Contains("H1")
                ) //Show room employee
            {
                ListItem item = new ListItem();
                item = new ListItem(aCC_ChartOfAccountLabel4.ChartOfAccountLabel4Text.ToString(), aCC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID.ToString());
                ddlRefference.Items.Add(item);
            }
        }

        if (getLogin().ExtraField5 != "1")
        {
            ddlWorkStationSearch.SelectedValue = getLogin().ExtraField5;
            ddlWorkStationSearch.Enabled = false;
        }
        else
        {
            ddlWorkStationSearch.Enabled = true;
        }
    }
    
    private void loadProductStatus()
    {
        ListItem li = new ListItem("Select Status", "0");
        ddlPos_ProductStatus.Items.Add(li);

        List<Pos_ProductStatus> productStatuss = new List<Pos_ProductStatus>();
        productStatuss = Pos_ProductStatusManager.GetAllPos_ProductStatuss();
        foreach (Pos_ProductStatus productStatus in productStatuss)
        {
            ListItem item = new ListItem(productStatus.ProductStatusName.ToString(), productStatus.Pos_ProductStatusID.ToString());
            ddlPos_ProductStatus.Items.Add(item);
        }
    }
    private void loadPos_Size()
    {
        ListItem li = new ListItem("Any Size", "0");
        ddlPos_Size.Items.Add(li);

        List<Pos_Size> pos_Sizes = new List<Pos_Size>();
        pos_Sizes = Pos_SizeManager.GetAllPos_Sizes();
        foreach (Pos_Size pos_Size in pos_Sizes)
        {
            ListItem item = new ListItem(pos_Size.SizeName.ToString(), pos_Size.Pos_SizeID.ToString());
            ddlPos_Size.Items.Add(item);
        }
    }
    
    private void loadPos_Color()
    {
        ListItem li = new ListItem("Select Color...", "0");
        ddlColorSearch.Items.Add(li);

        List<Pos_Color> pos_Colors = new List<Pos_Color>();
        pos_Colors = Pos_ColorManager.GetAllPos_Colors();
        foreach (Pos_Color pos_Color in pos_Colors)
        {
            ListItem item = new ListItem(pos_Color.ColorName.ToString(), pos_Color.Pos_ColorID.ToString());
            ddlColorSearch.Items.Add(item);
        }
    }

    private void showPos_ProductGrid()
    {
        gvPos_Product.DataSource = Pos_ProductManager.GetAllPos_Products();
        gvPos_Product.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string sql = @"SELECT [Pos_Product].[Pos_ProductID]
      ,[Pos_Product].[ProductID]
      ,[Pos_Product].[ReferenceID]
      ,[Pos_Product].[Pos_ProductTypeID]
      ,[Pos_Product].[Inv_UtilizationDetailsIDs]
      ,[Pos_Product].[ProductStatusID]
      ,[Pos_Product].[DesignCode]
      ,[Pos_Product].[Pos_SizeID]
      ,[Pos_Product].[Pos_BrandID]
      ,[Pos_Product].[Inv_QuantityUnitID]
      ,[Pos_Product].[FabricsCost]
      ,[Pos_Product].[AccesoriesCost]
      ,[Pos_Product].[Overhead]
      ,[Pos_Product].[OthersCost]
      ,[Pos_Product].[PurchasePrice]
      ,[TotalCostPerProduct] =([Pos_Product].[FabricsCost] + [Pos_Product].[AccesoriesCost] + [Pos_Product].[Overhead]+[Pos_Product].[OthersCost]+[Pos_Product].[PurchasePrice])
      ,[Pos_Product].[SalePrice]
      ,[Pos_Product].[OldSalePrice]
      ,[Pos_Product].[Note]
      ,[Pos_Product].[BarCode]
      ,[Pos_Product].[Pos_ColorID]
      ,[Pos_Product].[Pos_FabricsTypeID]
      ,[Pos_Product].[StyleCode]
      ,[Pos_Product].[Pic1]
      ,[Pos_Product].[Pic2]
      ,[Pos_Product].[Pic3]
      ,[VatPercentage]=(case WorkStation.ExtraField3 when '1' then cast(ACC_ChartOfAccountLabel4.ExtraField3 as decimal(10,2)) else 0.00 end)
      ,[VatPercentageAlways] =cast(ACC_ChartOfAccountLabel4.ExtraField3 as decimal(10,2))
      ,[Pos_Product].[IsVatExclusive]
      ,[Pos_Product].[DiscountPercentage]
      ,[Pos_Product].[DiscountAmount]
      ,[Pos_Product].[FabricsNo]
      ,Pos_WorkStationStock.Stock
      ,(Pos_WorkStationStock.Stock *[Pos_Product].[SalePrice]) as StockSalePrice
      ,ACC_ChartOfAccountLabel4.ChartOfAccountLabel4Text as ProductName
      ,Inv_QuantityUnit.QuantityUnitName
      ,cast(([Pos_Product].[FabricsCost]
      +[Pos_Product].[AccesoriesCost]
      +[Pos_Product].[Overhead]
      +[Pos_Product].[OthersCost]
      +[Pos_Product].[PurchasePrice]) as nvarchar(256)) as Cost
      ,Pos_Color.ColorName
      ,Pos_Size.SizeName
      ,Pos_ProductType.ProductTypeName
      ,Pos_ProductStatus.ProductStatusName
      ,Pos_Brand.BrandName
      ,[Pos_Product].[ExtraField10]
      ,[Pos_Product].[AddedBy]
      ,[Pos_Product].[AddedDate]
      ,[Pos_Product].[UpdatedBy]
      ,[Pos_Product].[UpdatedDate]
      ,[Pos_Product].[RowStatusID]
  FROM [Pos_Product]
  inner join Pos_WorkStationStock on [Pos_Product].Pos_ProductID = Pos_WorkStationStock.ProductID
  inner join ACC_ChartOfAccountLabel4 on ACC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID=Pos_Product.ProductID
  inner join ACC_ChartOfAccountLabel4 as WorkStation on WorkStation.ACC_ChartOfAccountLabel4ID=Pos_WorkStationStock.WorkStationID
  inner join Inv_QuantityUnit on Inv_QuantityUnit.Inv_QuantityUnitID = Pos_Product.Inv_QuantityUnitID
  inner join Pos_Color on Pos_Color.Pos_ColorID = Pos_Product.Pos_ColorID
  inner join Pos_Size on Pos_Size.Pos_SizeID = Pos_Product.Pos_SizeID
  inner join Pos_ProductType on Pos_ProductType.Pos_ProductTypeID = Pos_Product.Pos_ProductTypeID
  inner join Pos_ProductStatus on Pos_ProductStatus.Pos_ProductStatusID = Pos_Product.ProductStatusID
  inner join Pos_Brand on Pos_Brand.Pos_BrandID = Pos_Product.Pos_BrandID
where Pos_WorkStationStock.Stock >0 and Pos_WorkStationStock.WorkStationID = " + ddlWorkStationSearch.SelectedValue + @"
";

        if (ddlProduct.SelectedValue != "0")
        {
            sql += " and [Pos_Product].ProductID="+ddlProduct.SelectedValue;
        }

        if (txtDesignCode.Text != "")
        {
            sql += " and [Pos_Product].DesignCode=" + txtDesignCode.Text;
        }

        if (txtBarCode.Text != "")
        {
            sql += " and [Pos_Product].BarCode='" + txtBarCode.Text+"'";
        }

        if (ddlPos_Size.SelectedValue != "0")
        {
            sql += " and [Pos_Product].Pos_SizeID=" + ddlPos_Size.SelectedValue;
        }


        if (ddlColorSearch.SelectedValue != "0")
        {
            sql += " and [Pos_Product].Pos_ColorID=" + ddlColorSearch.SelectedValue;
        }


        if (ddlPos_ProductStatus.SelectedValue != "0")
        {
            sql += " and [Pos_Product].ProductStatusID=" + ddlPos_ProductStatus.SelectedValue;
        }

        sql += " order by ACC_ChartOfAccountLabel4.ChartOfAccountLabel4Text,Pos_Size.SizeName,[Pos_Product].[BarCode],Pos_Color.ColorName";
        DataSet ds = CommonManager.SQLExec(sql);

        gvPos_Product.DataSource = ds.Tables[0];
        gvPos_Product.DataBind();

        decimal totalStock = 0;
        decimal totalAmount = 0;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            totalAmount += decimal.Parse(dr["StockSalePrice"].ToString());
            totalStock += decimal.Parse(dr["Stock"].ToString());
        }

        try
        {
            ((Label)gvPos_Product.FooterRow.FindControl("lblStockFooter")).Text = totalStock.ToString("0,0");
            ((Label)gvPos_Product.FooterRow.FindControl("lblStockSalePriceFooter")).Text = totalAmount.ToString("0,0.00");
        }
        catch (Exception ex)
        { }
        //loadSales person
        ddlSalesPerson.Items.Clear();
        foreach (ListItem item in ddlSalesPersonAll.Items)
        {
            if (int.Parse(ddlWorkStationSearch.SelectedItem.Text.Split('-')[1]) == int.Parse(item.Text.Split('-')[0]))
            {
                ddlSalesPerson.Items.Add(new ListItem(item.Text, item.Value));
            }
        }
    }

    

    private void showAlartMessage(string message)
    {
        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
             "err_msg",
             "alert('" + message + "');",
             true);
    }

    private void loadLoginInHiddenField()
    {
        if (hfLoginID.Value == "")
        {
            hfLoginID.Value = getLogin().LoginID.ToString();
        }
    }

    private Login getLogin()
    {
        Login login = new Login();

        try
        {
            if (Session["Login"] != null)
            {
                login = (Login)Session["Login"];
            }
            else if (hfLoginID.Value != "")
            {
                login = LoginManager.GetLoginByID(int.Parse(hfLoginID.Value));
            }
            else
            { Session["PreviousPage"] = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect("../LoginPage.aspx"); }

        }
        catch (Exception ex)
        { }

        return login;
    }
    private string GetTransactionMasterID()
    {
        txtOldTransactionID.Text = txtOldTransactionID.Text.Trim();

        string transactionMasterID = "0";
        string sqlTransaction = "select Pos_TransactionMasterID from Pos_TransactionMaster where TransactionID=" + txtOldTransactionID.Text
                   + " and Pos_TransactionTypeID =" + Request.QueryString["TransactionTypeID"] + ";";

        DataSet ds = CommonManager.SQLExec(sqlTransaction);

        if (ds.Tables[0].Rows.Count == 0)
        {
            return "0";
        }
        else
        {
            transactionMasterID = ds.Tables[0].Rows[0][0].ToString();
        }

        return transactionMasterID;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        CompleteTheAutoCalculation();

        if (decimal.Parse(txtReturnAmount.Text) > decimal.Parse(txtPayableAmount.Text))
        {
            showAlartMessage("We can not Refund the money please buy other more product.");
            return;
        }

        if (decimal.Parse(txtRefundOrDue.Text) < 0)
        {
            showAlartMessage("Payment amount is less than the billing Amount");
            return;
        }

        
        if (decimal.Parse(txtRefundOrDue.Text) > decimal.Parse(txtCashAmount.Text)
            )
        {
            showAlartMessage("Your cash payment is less than refund amount");
            return;
        }


        

        Pos_TransactionMaster pos_TransactionMasterReturn = new Pos_TransactionMaster();
        pos_TransactionMasterReturn.Pos_TransactionMasterID = 0;

        string sqlReturn = "";
        string accountsEntry = @""; 
   
        if (Request.QueryString["TransactionTypeID"] =="14")
        {
            decimal totalReturnAmount = 0;
            decimal totalReturnAmountVat = 0;
            decimal totalReturnAmountSaleprice = 0;
            decimal totalReturnAmountDiscount = 0;
            string InvoiceNo = "";

            
            
            bool isRetrun = false;
            foreach (GridViewRow gvr in gvReturnInvoice.Rows)
            {
                TextBox txtRtnQty = (TextBox)gvr.FindControl("txtRtnQty");
                Label lblSoldQty = (Label)gvr.FindControl("lblSoldQty");
                Label lblInvoiceNo = (Label)gvr.FindControl("lblInvoiceNo");
                Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
                Label lblDiscountAmount = (Label)gvr.FindControl("lblDiscountAmount");
                Label lblVat = (Label)gvr.FindControl("lblVat");
                Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");
                Label lblTotal = (Label)gvr.FindControl("lblTotal");
           
                HiddenField hfPos_TransactionID = (HiddenField)gvr.FindControl("hfPos_TransactionID");
                HiddenField hfPos_TransactionMasterID = (HiddenField)gvr.FindControl("hfPos_TransactionMasterID");
                HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");

                if (txtRtnQty.Text != "0" && txtRtnQty.Text != "")
                {
                    if (!isRetrun)
                    {
                        pos_TransactionMasterReturn.TransactionDate = (txtBackDatedSale.Text == DateTime.Now.ToString("dd MMM yyyy") ? DateTime.Now : DateTime.Parse(txtBackDatedSale.Text)); 
                        pos_TransactionMasterReturn.TransactionID = 0;
                        pos_TransactionMasterReturn.Pos_TransactionTypeID = 14;
                        pos_TransactionMasterReturn.ToOrFromID = int.Parse(txtCustomerID.Text == "" ? "0" : txtCustomerID.Text);
                        pos_TransactionMasterReturn.Record = ddlSalesPerson.SelectedValue;
                        pos_TransactionMasterReturn.Particulars = "";
                        pos_TransactionMasterReturn.WorkSatationID = int.Parse(ddlWorkStationSearch.SelectedValue);
                        pos_TransactionMasterReturn.ExtraField1 = decimal.Parse(txtReturnAmount.Text).ToString("0.00");
                        pos_TransactionMasterReturn.ExtraField2 = lblInvoiceNo.Text;
                        pos_TransactionMasterReturn.ExtraField3 = txtCustomerName.Text;
                        pos_TransactionMasterReturn.ExtraField4 = txtContactNo.Text;
                        pos_TransactionMasterReturn.ExtraField5 = txtCardNo.Text;
                        pos_TransactionMasterReturn.AddedBy = getLogin().LoginID;
                        pos_TransactionMasterReturn.AddedDate = DateTime.Now;
                        pos_TransactionMasterReturn.UpdatedBy = getLogin().LoginID;
                        pos_TransactionMasterReturn.UpdatedDate = DateTime.Now;
                        pos_TransactionMasterReturn.RowStatusID = 1;
                        pos_TransactionMasterReturn.Pos_TransactionMasterID = Pos_TransactionMasterManager.InsertPos_TransactionMaster(pos_TransactionMasterReturn);
                
                        isRetrun = true;
                    }

                    totalReturnAmount += ((decimal.Parse(lblTotal.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                    totalReturnAmountSaleprice += ((decimal.Parse(lblStockSalePrice.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                    totalReturnAmountVat += ((decimal.Parse(lblVat.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                    totalReturnAmountDiscount += ((decimal.Parse(lblDiscountAmount.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));

                    sqlReturn += "Update Pos_TransactionMaster set UpdatedDate=GetDate(), Particulars= cast(Particulars as nvarchar(max))+'<hr/>Sales Return(" + lblBarCode.Text.Trim() + @"-" + txtRtnQty.Text + @")' where Pos_TransactionMasterID=" + hfPos_TransactionMasterID.Value + ";";
                    sqlReturn += "Update Pos_Transaction set  UpdatedDate=GetDate(),UpdatedBy=" + getLogin().LoginID.ToString() + @" ,ExtraField4= (cast(ExtraField4 as int)+" + txtRtnQty.Text + ") where Pos_TransactionID=" + hfPos_TransactionID.Value + ";";
                    sqlReturn += "update Pos_WorkStationStock set Stock+=" + txtRtnQty.Text + " where WorkStationID=" + ddlWorkStationSearch.SelectedValue + " and ProductID=" + hfPos_ProductID.Value + ";";

                    
                    Pos_Transaction pos_Transaction = new Pos_Transaction();

                    pos_Transaction.Pos_ProductID = Int32.Parse(hfPos_ProductID.Value);
                    pos_Transaction.Quantity = Decimal.Parse(txtRtnQty.Text);
                    pos_Transaction.Pos_ProductTrasactionTypeID = 14;
                    pos_Transaction.Pos_ProductTransactionMasterID = pos_TransactionMasterReturn.Pos_TransactionMasterID;
                    pos_Transaction.WorkStationID = Int32.Parse(ddlWorkStationSearch.SelectedValue);
                    pos_Transaction.ExtraField1 = ((decimal.Parse(lblDiscountAmount.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text)).ToString("0,0.00");
                    pos_Transaction.ExtraField2 = ((decimal.Parse(lblVat.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text)).ToString("0,0.00");
                    pos_Transaction.ExtraField3 = "Journal Details ID";
                    pos_Transaction.ExtraField4 = hfPos_TransactionID.Value;
                    pos_Transaction.ExtraField5 = ddlRefference.SelectedValue;
                    pos_Transaction.AddedBy = getLogin().LoginID;
                    pos_Transaction.AddedDate = DateTime.Now;
                    pos_Transaction.UpdatedBy = getLogin().LoginID;
                    pos_Transaction.UpdatedDate = DateTime.Now;
                    pos_Transaction.RowStatusID = 1;
                    int resutl = Pos_TransactionManager.InsertPos_Transaction(pos_Transaction);
                }
            }
        }

        int transactionTypeID = 13;//int.Parse(Request.QueryString["TransactionTypeID"]);

        int TransactionMasterID = 0;
        if (txtOldTransactionID.Text != "")
        {
            if (txtOldTransactionID.Text != "0")
            {
                TransactionMasterID = int.Parse(GetTransactionMasterID());
            }
            else
            {
                TransactionMasterID = int.Parse(txtOldTransactionID.Text);
            }

            if (TransactionMasterID == 0)
            {
                showAlartMessage("Wrong old ID");
                return;
            }
        }
        else
        {
            Pos_TransactionMaster pos_TransactionMaster = new Pos_TransactionMaster();

            pos_TransactionMaster.TransactionDate = (txtBackDatedSale.Text == DateTime.Now.ToString("dd MMM yyyy") ? DateTime.Now : DateTime.Parse(txtBackDatedSale.Text));
            pos_TransactionMaster.TransactionID = 0;
            pos_TransactionMaster.Pos_TransactionTypeID = transactionTypeID;
            pos_TransactionMaster.ToOrFromID = int.Parse(txtCustomerID.Text == "" ? "0" : txtCustomerID.Text);
            pos_TransactionMaster.Record = ddlSalesPerson.SelectedValue;
            pos_TransactionMaster.Particulars = txtNote.Text;
            pos_TransactionMaster.WorkSatationID = int.Parse(ddlWorkStationSearch.SelectedValue);
            pos_TransactionMaster.ExtraField1 = decimal.Parse(txtCashAmount.Text).ToString("0.00");
            pos_TransactionMaster.ExtraField2 = decimal.Parse(txtCardAmount.Text).ToString("0.00");
            pos_TransactionMaster.ExtraField3 = txtCustomerName.Text;
            pos_TransactionMaster.ExtraField4 = txtContactNo.Text;
            pos_TransactionMaster.ExtraField5 = decimal.Parse(txtRefundOrDue.Text).ToString("0.00");
            pos_TransactionMaster.AddedBy = getLogin().LoginID;
            pos_TransactionMaster.AddedDate = DateTime.Now;
            pos_TransactionMaster.UpdatedBy = (pos_TransactionMasterReturn.Pos_TransactionMasterID == 0 ? getLogin().LoginID : ((-1) * pos_TransactionMasterReturn.Pos_TransactionMasterID));
            pos_TransactionMaster.UpdatedDate = DateTime.Now;
            pos_TransactionMaster.RowStatusID = 1;
            TransactionMasterID = Pos_TransactionMasterManager.InsertPos_TransactionMaster(pos_TransactionMaster);
            pos_TransactionMaster = Pos_TransactionMasterManager.GetPos_TransactionMasterByID(TransactionMasterID);

            txtOldTransactionID.Text = pos_TransactionMaster.TransactionID.ToString();

            accountsEntry += @"
                                Declare @JournalMasterID int
                                Declare @ProductID int
                                Declare @CostOfGoodsSold decimal(18,2)
                                INSERT INTO [ACC_JournalMaster]
                                           ([JournalMasterName]
                                           ,[ExtraField1]
                                           ,[ExtraField2]
                                           ,[ExtraField3]
                                           ,[Note]
                                           ,[JournalDate]
                                           ,[AddedBy]
                                           ,[AddedDate]
                                           ,[UpdatedBy]
                                           ,[UpdatedDate]
                                           ,[RowStatusID])
                                     VALUES
                                           ('1'--<JournalMasterName, nvarchar(50),>
                                           ,''--<ExtraField1, nvarchar(256),>
                                           ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                           ,'" + TransactionMasterID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                           ,'Sales inv#" + pos_TransactionMaster.TransactionID + @" in " + ddlWorkStationSearch.SelectedItem.Text + @"'--<Note, nvarchar(256),>
                                           ,GETDATE()--<JournalDate, datetime,>
                                           ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                           ,GETDATE()--<AddedDate, datetime,>
                                           ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                           ,GETDATE()--<UpdatedDate, datetime,>
                                           ,1--<RowStatusID, int,>
                                           );
                                Set @JournalMasterID = SCOPE_IDENTITY();
                                ";

            #region For Sales return Journal Entry
            if (Request.QueryString["TransactionTypeID"] == "14")
            {
                
                foreach (GridViewRow gvr in gvReturnInvoice.Rows)
                {
                    TextBox txtRtnQty = (TextBox)gvr.FindControl("txtRtnQty");
                    Label lblSoldQty = (Label)gvr.FindControl("lblSoldQty");
                    Label lblInvoiceNo = (Label)gvr.FindControl("lblInvoiceNo");
                    Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
                    Label lblDiscountAmount = (Label)gvr.FindControl("lblDiscountAmount");
                    Label lblVat = (Label)gvr.FindControl("lblVat");
                    Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");
                    Label lblTotal = (Label)gvr.FindControl("lblTotal");

                    HiddenField hfPos_TransactionID = (HiddenField)gvr.FindControl("hfPos_TransactionID");
                    HiddenField hfPos_TransactionMasterID = (HiddenField)gvr.FindControl("hfPos_TransactionMasterID");
                    HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");
                    HiddenField hfVatPercentageAlways = (HiddenField)gvr.FindControl("hfVatPercentageAlways");
                    HiddenField hfTotalCostPerProduct = (HiddenField)gvr.FindControl("hfTotalCostPerProduct");
                    
                    if (txtRtnQty.Text != "0" && txtRtnQty.Text != "")
                    {
                        
                        
                        decimal salesIncome = ((decimal.Parse(lblStockSalePrice.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                        decimal discount = ((decimal.Parse(lblDiscountAmount.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                        decimal VAT = ((decimal.Parse(lblVat.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));

                        #region Cost of Good Seles(Expence)	Finished Goods(Asset)

                        //Finished Good(Aseet)
                        accountsEntry += @"
                            Set @ProductID=(Select ProductID from Pos_Product where Pos_ProductID=" + hfPos_ProductID.Value + @")
                            set @CostOfGoodsSold=(select ([Pos_Product].[FabricsCost] + [Pos_Product].[AccesoriesCost] + [Pos_Product].[Overhead]+[Pos_Product].[OthersCost]+[Pos_Product].[PurchasePrice]) from Pos_Product where Pos_ProductID=" + hfPos_ProductID.Value + @")
                            INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,9--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,(@CostOfGoodsSold *" + decimal.Parse(txtRtnQty.Text).ToString("0.00") + @")--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";

                        //Cost of Good Seles(Expence)
                        accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,236--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ,(@CostOfGoodsSold *" + decimal.Parse(txtRtnQty.Text).ToString("0.00") + @")--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                        #endregion

                        #region Other Journal Entry for each product

                        accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,235--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + salesIncome.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                        if (VAT > 0) //Excluding vat
                        {
                            accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,57--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + VAT.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Excluding'--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                        }
                        else //including vat
                        {
                            try
                            {
                                VAT = ((salesIncome-discount) * decimal.Parse(hfVatPercentageAlways.Value) / 100);
                                accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,57--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + VAT.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Including'--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";

                                accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,235--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ," + VAT.ToString("0.00") + @"--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Including'--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                            }
                            catch (Exception ex)
                            { }
                        }

                        if (discount > 0)
                        {
                            accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,181--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ," + discount.ToString("0.00") + @"--<Credit, decimal(20,2),>
                                   ,'" + hfPos_TransactionID.Value + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                        }

                        #endregion
                    }
                }
            }
            #endregion

            #region JOurnal for money
            decimal cashAmount = decimal.Parse(txtCashAmount.Text) - decimal.Parse(txtRefundOrDue.Text);
            if (cashAmount > 0)
            {
                accountsEntry += @"
                              INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,1--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + cashAmount.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,''--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                                ";
            }
            //Card payment
            foreach (GridViewRow gvr in gvPayment.Rows)
            {
                HiddenField hfSerial = (HiddenField)gvr.FindControl("hfSerial");
                HiddenField hfIssueFromID = (HiddenField)gvr.FindControl("hfIssueFromID");
                Label lblCardNo = (Label)gvr.FindControl("lblCardNo");
                Label lblCardType = (Label)gvr.FindControl("lblCardType");
                Label lblIssueFrom = (Label)gvr.FindControl("lblIssueFrom");
                Label lblAmount = (Label)gvr.FindControl("lblAmount");

                Pos_Product PaymentGrid = new Pos_Product();
                PaymentGrid.Pos_ProductID = int.Parse(hfSerial.Value);
                PaymentGrid.ExtraField1 = lblCardNo.Text;
                PaymentGrid.ExtraField2 = lblCardType.Text;
                PaymentGrid.ExtraField3 = lblIssueFrom.Text;
                PaymentGrid.ExtraField4 = hfIssueFromID.Value;
                PaymentGrid.ExtraField5 = lblAmount.Text;

                /*
                 aCC_JournalDetail.ACC_ChartOfAccountLabel4ID = 823;
            aCC_JournalDetail.ACC_ChartOfAccountLabel4Text = "CITY BANK - GentlePark (1401307973001)";
                     
                 aCC_JournalDetail.ACC_ChartOfAccountLabel4ID = 828;
            aCC_JournalDetail.ACC_ChartOfAccountLabel4Text = "DBBL-126-110-11033";
                 */
                accountsEntry += @"
                              INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ," + (lblIssueFrom.Text.Trim() == "City Bank" ? "823" : "828") + @"--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,3--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + lblAmount.Text + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + lblCardType.Text + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'" + lblCardNo.Text + @"'--<ExtraField1, nvarchar(256),>
                                   ," + pos_TransactionMaster.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_TransactionMaster.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                                ";
            }


        }
            #endregion
           

        string sql =sqlReturn+ "Declare @Count int; ";

        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");
            TextBox txtQty = (TextBox)gvr.FindControl("txtQty");
            TextBox txtDiscountAmountTotal = (TextBox)gvr.FindControl("txtDiscountAmountTotal");
            TextBox txtVatGridTotal = (TextBox)gvr.FindControl("txtVatGridTotal");
            Label lblSubTotalSalePrice = (Label)gvr.FindControl("lblSubTotalSalePrice");
            HiddenField hfVatPercentageAlways = (HiddenField)gvr.FindControl("hfVatPercentageAlways");
            HiddenField hfTotalCostPerProduct = (HiddenField)gvr.FindControl("hfTotalCostPerProduct");

            if (txtQty.Text == "")
                continue;
            if (decimal.Parse(txtQty.Text) == 0)
                continue;

            Pos_Transaction pos_Transaction = new Pos_Transaction();

            pos_Transaction.Pos_ProductID = Int32.Parse(hfPos_ProductID.Value);
            pos_Transaction.Quantity = Decimal.Parse(txtQty.Text);
            pos_Transaction.Pos_ProductTrasactionTypeID = transactionTypeID;
            pos_Transaction.Pos_ProductTransactionMasterID = TransactionMasterID;
            pos_Transaction.WorkStationID = Int32.Parse(ddlWorkStationSearch.SelectedValue);
            pos_Transaction.ExtraField1 = txtDiscountAmountTotal.Text;
            pos_Transaction.ExtraField2 = txtVatGridTotal.Text;
            pos_Transaction.ExtraField3 = "Journal Details ID";
            pos_Transaction.ExtraField4 = "0";
            pos_Transaction.ExtraField5 = ddlRefference.SelectedValue;
            pos_Transaction.AddedBy = getLogin().LoginID;
            pos_Transaction.AddedDate = DateTime.Now;
            pos_Transaction.UpdatedBy = getLogin().LoginID;
            pos_Transaction.UpdatedDate = DateTime.Now;
            pos_Transaction.RowStatusID = 1;
            pos_Transaction.Pos_TransactionID = Pos_TransactionManager.InsertPos_Transaction(pos_Transaction);

            /*
             
             235 (Sales Revenue ( Income -> Sales Revenue))
             * 181 Discount for all sales ( Expense -> Expence-1)
             * 57 Vat Payable-1 ( Current Liabilities -> VAT Payable)
             */

            decimal salesIncome = decimal.Parse(lblSubTotalSalePrice.Text);
            decimal discount = decimal.Parse(txtDiscountAmountTotal.Text);
            decimal VAT = decimal.Parse(txtVatGridTotal.Text);
            salesIncome = (salesIncome - VAT + discount);
            #region Cost of Good Seles(Expence)	Finished Goods(Asset)

            //Finished Good(Aseet)
            accountsEntry += @"
                            Set @ProductID=(Select ProductID from Pos_Product where Pos_ProductID=" + hfPos_ProductID.Value + @")
                            set @CostOfGoodsSold=(select ([Pos_Product].[FabricsCost] + [Pos_Product].[AccesoriesCost] + [Pos_Product].[Overhead]+[Pos_Product].[OthersCost]+[Pos_Product].[PurchasePrice]) from Pos_Product where Pos_ProductID=" + hfPos_ProductID.Value + @")
                            INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,9--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ,(@CostOfGoodsSold *" +  Decimal.Parse(txtQty.Text).ToString("0.00") + @")--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";

            //Cost of Good Seles(Expence)
            accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,236--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,(@CostOfGoodsSold *" +  Decimal.Parse(txtQty.Text).ToString("0.00") + @")--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
            #endregion

            #region Other Journal Entry for each product
            
            accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,235--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ,"+salesIncome.ToString("0.00")+@"--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
            if (VAT > 0) //Excluding vat
            {
                accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,57--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ," + VAT.ToString("0.00") + @"--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Excluding'--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
            }
            else //including vat
            {
                try
                {
                    VAT = ((salesIncome-discount) * decimal.Parse(hfVatPercentageAlways.Value) / 100);
                    accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,57--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ,0--<Debit, decimal(20,2),>
                                   ," + VAT.ToString("0.00") + @"--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Including'--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";

                    accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,235--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," + VAT.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,'Including'--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
                }
                catch (Exception ex)
                { }
            }

            if (discount > 0)
            {
                    accountsEntry += @"
                        INSERT INTO [ACC_JournalDetail]
                                   ([JournalMasterID]
                                   ,[ACC_ChartOfAccountLabel4ID]
                                   ,[ACC_ChartOfAccountLabel3ID]
                                   ,[WorkStation]
                                   ,[Debit]
                                   ,[Credit]
                                   ,[ExtraField3]
                                   ,[ExtraField2]
                                   ,[ExtraField1]
                                   ,[AddedBy]
                                   ,[AddedDate]
                                   ,[UpdatedBy]
                                   ,[UpdatedDate]
                                   ,[RowStatusID])
                             VALUES
                                   (@JournalMasterID--<JournalMasterID, int,>
                                   ,@ProductID--<ACC_ChartOfAccountLabel4ID, int,>
                                   ,181--<ACC_ChartOfAccountLabel3ID, int,>
                                   ," + ddlWorkStationSearch.SelectedValue + @"--<WorkStation, int,>
                                   ," +  discount.ToString("0.00") + @"--<Debit, decimal(20,2),>
                                   ,0--<Credit, decimal(20,2),>
                                   ,'" + pos_Transaction.Pos_TransactionID.ToString() + @"'--<ExtraField3, nvarchar(256),>
                                   ,'POS SALE'--<ExtraField2, nvarchar(256),>
                                   ,''--<ExtraField1, nvarchar(256),>
                                   ," + pos_Transaction.AddedBy.ToString() + @"--<AddedBy, int,>
                                    ,GETDATE()--<AddedDate, datetime,>
                                    ," + pos_Transaction.AddedBy.ToString() + @"--<UpdatedBy, int,>
                                    ,GETDATE()--<UpdatedDate, datetime,>
                                    ,1--<RowStatusID, int,>
                                   )  ;
                            ";
            }

            #endregion

            bool IsGeneralOperation = false;

            switch (transactionTypeID)
            {
                case 9: //Issue
                    IsGeneralOperation = true;
                    break;

                case 13: //Sales
                    IsGeneralOperation = true;
                    break;
                default:
                    break;
            }

            if (IsGeneralOperation)
            {
                sql += @"
                        set @Count=
                        (
                        select COUNT(*) from Pos_WorkStationStock
                        where ProductID=" + pos_Transaction.Pos_ProductID.ToString() + @" and WorkStationID="+ddlWorkStationSearch.SelectedValue+@"
                        )

                        if @Count = 0
                        BEGIN
	                        INSERT INTO [Pos_WorkStationStock]
                                    ([WorkStationID]
                                    ,[ProductID]
                                    ,[Stock])
                                    VALUES(" + ddlWorkStationSearch.SelectedValue + @"," + pos_Transaction.Pos_ProductID.ToString() + @"," + txtQty.Text + @");
                        END
                        ELSE
                        BEGIN
                            Update Pos_WorkStationStock set Stock -= " + txtQty.Text + @" where ProductID=" + pos_Transaction.Pos_ProductID.ToString() + @" and WorkStationID=" + ddlWorkStationSearch.SelectedValue + @";
                        END;";
                
            }
        }

        CommonManager.SQLExec(sql + ";" + accountsEntry);
        //btnSearch_Click(this, new EventArgs());
        //hlnkProductionPrint.Visible = true;
        //hlnkProductionPrint.NavigateUrl = "SalesPrint.aspx?Pos_TransactionMasterID=" + TransactionMasterID.ToString();
        Response.Redirect("SalesPrint.aspx?Pos_TransactionMasterID=" + TransactionMasterID.ToString());
    }

    private void CompleteTheAutoCalculation()
    {
        //credit card calculation
        if (txtAmount.Text != "")
        {
            btnAddCardPayment_Click(this, new EventArgs());
        }
        //cash amount calculation
        //it has been calculated autometically
        //if (txtCashAmount.Text != "")
        //{
        //    if (decimal.Parse(txtCashAmount.Text) != 0)
        //    {
        //        txtCashAmount_TextChanged(this, new EventArgs());
        //    }
        //}
    }
    protected void txtContactNo_TextChanged(object sender, EventArgs e)
    {
        txtCustomerID.Text = "";
        txtCardNo.Text = "";

        SearchCustomer();
    }

    protected void txtCustomerID_TextChanged(object sender, EventArgs e)
    {
        txtContactNo.Text = "";
        txtCardNo.Text = "";
        SearchCustomer();
    }
    protected void txtCardNo_TextChanged(object sender, EventArgs e)
    {
        txtContactNo.Text = "";
        txtCustomerID.Text = "";

        SearchCustomer();
    }

    private void SearchCustomer()
    {
        string sql = "Select Pos_CustomerID,CardNo,CustomerName,Address,Mobile,DiscountPersent from Pos_Customer where RowSatatusID=1 ";
        if (txtCardNo.Text != "")
        {
            sql += " and CardNo='" + txtCardNo.Text+"'";
        }

        if (txtCustomerID.Text != "")
        {
            sql += " and Pos_CustomerID=" + txtCustomerID.Text;
        }

        if (txtContactNo.Text != "")
        {
            sql += " and Mobile='" + txtContactNo.Text + "'";
        }


        DataSet ds = CommonManager.SQLExec(sql);

        if (ds.Tables[0].Rows.Count > 0)
        {
            txtCustomerName.Text = ds.Tables[0].Rows[0]["CustomerName"].ToString();
            txtCustomerAddress.Text = ds.Tables[0].Rows[0]["Address"].ToString();
            txtCardNo.Text = ds.Tables[0].Rows[0]["CardNo"].ToString();
            txtCustomerID.Text = ds.Tables[0].Rows[0]["Pos_CustomerID"].ToString();
            txtContactNo.Text = ds.Tables[0].Rows[0]["Mobile"].ToString();
            txtDiscountPercentage.Text = ds.Tables[0].Rows[0]["DiscountPersent"].ToString();
            txtDiscountPercentage.Enabled = false;

            if (txtDiscountPercentage.Text != "")
            {
                btnApplyDiscount_Click(this, new EventArgs());
            }
        }
        else
            txtDiscountPercentage.Enabled = true;

    }
    protected void btnAddToPreview_Click(object sender, EventArgs e)
    {
        List<Pos_Product> takenFromSearchProduct = new List<Pos_Product>();

        foreach (GridViewRow gvr in gvPos_Product.Rows)
        {
            Pos_Product prod = new Pos_Product();

            HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");
            
            Label lblProductName = (Label)gvr.FindControl("lblProductName");
            Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
            Label lblSizeName = (Label)gvr.FindControl("lblSizeName");
            Label lblColorName = (Label)gvr.FindControl("lblColorName");
            Label lblProductStatusName = (Label)gvr.FindControl("lblProductStatusName");
            Label lblStock = (Label)gvr.FindControl("lblStock");
            Label lblSalePrice = (Label)gvr.FindControl("lblSalePrice");
            Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");

            TextBox txtQty = (TextBox)gvr.FindControl("txtQty");
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");
            HiddenField hfVatPercentageAlways = (HiddenField)gvr.FindControl("hfVatPercentageAlways");
            HiddenField hfTotalCostPerProduct = (HiddenField)gvr.FindControl("hfTotalCostPerProduct");

            prod.Pos_ProductID = int.Parse(hfPos_ProductID.Value);
            prod.ProductName = lblProductName.Text;
            prod.BarCode = lblBarCode.Text;
            prod.ExtraField1 = txtQty.Text;
            prod.ExtraField10 = lblSizeName.Text;
            prod.ExtraField2 = lblColorName.Text;
            prod.ExtraField3 = lblProductStatusName.Text;
            prod.ExtraField4 = lblStock.Text;
            prod.ExtraField5 = lblSalePrice.Text;
            prod.ExtraField6 = (decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)).ToString("0,0.00");
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text) != 0 ? (decimal.Parse(txtDiscountAmountGrid.Text) * decimal.Parse(txtQty.Text)) : ((decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)) * (decimal.Parse(txtDiscountGrid.Text) / 100));
            prod.ExtraField8 = decimal.Parse(txtVatGrid.Text) == 0 ? "0.00" : ((decimal.Parse(prod.ExtraField6) - prod.DiscountAmount) * (decimal.Parse(txtVatGrid.Text) / 100)).ToString("0,0.00");
            prod.ExtraField9 = (decimal.Parse(prod.ExtraField6) - prod.DiscountAmount + decimal.Parse(prod.ExtraField8)).ToString("0,0.00");
            prod.ExtraField7 = "0";//not fund 
            prod.AccesoriesCost = decimal.Parse(prod.ExtraField8);
            prod.FabricsCost = prod.DiscountAmount;
            //rewrite
            prod.ExtraField8 = txtVatGrid.Text;
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text);
            prod.DiscountPercentage = decimal.Parse(txtDiscountGrid.Text);

            if (decimal.Parse(lblStock.Text) < decimal.Parse(txtQty.Text))
            {
                showAlartMessage("For "+lblBarCode.Text+"the Qty is more than the stock");
                continue;
            }

            prod.VatPercentage = decimal.Parse(hfVatPercentageAlways.Value);
            prod.OthersCost = decimal.Parse(hfTotalCostPerProduct.Value); //total cost 
            if (txtQty.Text != "0")
            takenFromSearchProduct.Add(prod);
        }

        List<Pos_Product> takenFromPreviewProduct = new List<Pos_Product>();

        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            Pos_Product prod = new Pos_Product();

            HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");

            Label lblProductName = (Label)gvr.FindControl("lblProductName");
            Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
            Label lblSizeName = (Label)gvr.FindControl("lblSizeName");
            Label lblColorName = (Label)gvr.FindControl("lblColorName");
            Label lblProductStatusName = (Label)gvr.FindControl("lblProductStatusName");
            Label lblStock = (Label)gvr.FindControl("lblStock");
            Label lblSalePrice = (Label)gvr.FindControl("lblSalePrice");
            Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");

            TextBox txtQty = (TextBox)gvr.FindControl("txtQty");
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");
            HiddenField hfVatPercentageAlways = (HiddenField)gvr.FindControl("hfVatPercentageAlways");
            HiddenField hfTotalCostPerProduct = (HiddenField)gvr.FindControl("hfTotalCostPerProduct");

            prod.Pos_ProductID = int.Parse(hfPos_ProductID.Value);
            prod.ProductName = lblProductName.Text;
            prod.BarCode = lblBarCode.Text;
            prod.ExtraField1 = txtQty.Text;
            prod.ExtraField10 = lblSizeName.Text;
            prod.ExtraField2 = lblColorName.Text;
            prod.ExtraField3 = lblProductStatusName.Text;
            prod.ExtraField4 = lblStock.Text;
            prod.ExtraField5 = lblSalePrice.Text;
            prod.ExtraField6 = (decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)).ToString("0,0.00");
            prod.ExtraField7 = "0";//not fund 
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text) != 0 ? (decimal.Parse(txtDiscountAmountGrid.Text)) : ((decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)) * (decimal.Parse(txtDiscountGrid.Text) / 100));
            prod.ExtraField8 = decimal.Parse(txtVatGrid.Text) == 0 ? "0.00" : ((decimal.Parse(prod.ExtraField6) - prod.DiscountAmount) * (decimal.Parse(txtVatGrid.Text) / 100)).ToString("0,0.00");
            prod.ExtraField9 = (decimal.Parse(prod.ExtraField6) - prod.DiscountAmount + decimal.Parse(prod.ExtraField8)).ToString("0,0.00");

            prod.AccesoriesCost = decimal.Parse(prod.ExtraField8);
            prod.FabricsCost = prod.DiscountAmount;
            
            //Rewrite
            prod.ExtraField8 = txtVatGrid.Text;
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text);
            prod.DiscountPercentage = decimal.Parse(txtDiscountGrid.Text);

            prod.VatPercentage = decimal.Parse(hfVatPercentageAlways.Value);
            prod.OthersCost = decimal.Parse(hfTotalCostPerProduct.Value); //total cost 

            if (txtQty.Text!="0")
                takenFromPreviewProduct.Add(prod);
        }

        foreach (Pos_Product previewProd in takenFromPreviewProduct)
        {
            foreach (Pos_Product searchProd in takenFromSearchProduct)
            {
                if (searchProd.Pos_ProductID == previewProd.Pos_ProductID)
                {
                    previewProd.ExtraField6 = searchProd.ExtraField6;
                    previewProd.DiscountAmount = searchProd.DiscountAmount;
                    previewProd.ExtraField8 = searchProd.ExtraField8;
                    previewProd.ExtraField9 = searchProd.ExtraField9;
                    previewProd.AccesoriesCost = searchProd.AccesoriesCost;
                    previewProd.FabricsCost = searchProd.FabricsCost;

                    previewProd.VatPercentage = searchProd.VatPercentage;
                    previewProd.OthersCost = searchProd.OthersCost;

                    searchProd.ExtraField7 = "1";
                }
            }
        }

        foreach (Pos_Product searchProd in takenFromSearchProduct)
        {
            if (searchProd.ExtraField7 == "0")
            {
                takenFromPreviewProduct.Add(searchProd);
            }
        }

        //foreach (Pos_Product prod in takenFromPreviewProduct)
        //{
        //    prod.ExtraField6 = (decimal.Parse(prod.ExtraField5) * decimal.Parse(prod.ExtraField1)).ToString("0,0.00");

        //}

        gvPreview.DataSource = takenFromPreviewProduct;
        gvPreview.DataBind();


        decimal totalStock = 0;
        decimal qty = 0;
        decimal totalAmount = 0;
        decimal SubtotalAmount = 0;
        decimal discountSum = 0;
        decimal vatSum = 0;
        foreach (Pos_Product prod in takenFromPreviewProduct)
        {
            totalAmount += decimal.Parse(prod.ExtraField6);
            SubtotalAmount += decimal.Parse(prod.ExtraField9);
            totalStock += decimal.Parse(prod.ExtraField4);
            qty += decimal.Parse(prod.ExtraField1);
            vatSum += prod.AccesoriesCost;
            discountSum += prod.FabricsCost;
        }

        try
        {
            ((Label)gvPreview.FooterRow.FindControl("lblStockFooter")).Text = totalStock.ToString("0,0");
            ((Label)gvPreview.FooterRow.FindControl("lblStockSalePriceFooter")).Text = totalAmount.ToString("0,0.00");
            ((Label)gvPreview.FooterRow.FindControl("lblQtyFooter")).Text = qty.ToString("0,0");
            ((Label)gvPreview.FooterRow.FindControl("lblSubTotalSalePriceFooter")).Text = SubtotalAmount.ToString("0,0.00");
            ((Label)gvPreview.FooterRow.FindControl("lblDiscountAmountTotalFooter")).Text = discountSum.ToString("0,0.00");
            ((Label)gvPreview.FooterRow.FindControl("lblVatGridTotalFooter")).Text = vatSum.ToString("0,0.00");
        }
        catch (Exception ex)
        { }
        txtSubTotal.Text = totalAmount.ToString("0,0.00");
        txtVat.Text = vatSum.ToString("0,0.00");
        txtDiscount.Text = discountSum.ToString("0,0.00");
        
        lblTotalQty.Text = qty.ToString("0,0");

        txtCashAmount_TextChanged(this, new EventArgs());
    }
    protected void btnAddCardPayment_Click(object sender, EventArgs e)
    {
        List<Pos_Product> paymentList = new List<Pos_Product>();
        decimal totalAmount = 0;
        foreach (GridViewRow gvr in gvPayment.Rows)
        {
            HiddenField hfSerial = (HiddenField)gvr.FindControl("hfSerial");
            HiddenField hfIssueFromID = (HiddenField)gvr.FindControl("hfIssueFromID");
            Label lblCardNo = (Label)gvr.FindControl("lblCardNo");
            Label lblCardType = (Label)gvr.FindControl("lblCardType");
            Label lblIssueFrom = (Label)gvr.FindControl("lblIssueFrom");
            Label lblAmount = (Label)gvr.FindControl("lblAmount");

            Pos_Product PaymentGrid = new Pos_Product();
            PaymentGrid.Pos_ProductID = int.Parse(hfSerial.Value);
            PaymentGrid.ExtraField1 = lblCardNo.Text;
            PaymentGrid.ExtraField2 = lblCardType.Text;
            PaymentGrid.ExtraField3 = lblIssueFrom.Text;
            PaymentGrid.ExtraField4 = hfIssueFromID.Value;
            PaymentGrid.ExtraField5 = lblAmount.Text;
            totalAmount += decimal.Parse(lblAmount.Text);

            paymentList.Add(PaymentGrid);
        }

        Pos_Product newPayment = new Pos_Product();
        newPayment.Pos_ProductID = paymentList.Count;
        newPayment.ExtraField1 = txtCardNoPayment.Text;
        newPayment.ExtraField2 = ddlCardType.SelectedValue;
        newPayment.ExtraField3 = ddlIssueBank.SelectedItem.Text;
        newPayment.ExtraField4 = ddlIssueBank.SelectedValue;
        newPayment.ExtraField5 = txtAmount.Text;
        totalAmount += decimal.Parse(txtAmount.Text);

        paymentList.Add(newPayment);

        gvPayment.DataSource = paymentList;
        gvPayment.DataBind();

        txtCardAmount.Text = totalAmount.ToString("0,0.00"); 
        ((Label)gvPayment.FooterRow.FindControl("lblTotalCardAmountFooter")).Text = totalAmount.ToString("0,0.00") ;
        txtCashAmount_TextChanged(this, new EventArgs());
    }

    protected void lbDeletePayment_Click(object sender, EventArgs e)
    {
        LinkButton linkButton = new LinkButton();
        linkButton = (LinkButton)sender;
        int id= Convert.ToInt32(linkButton.CommandArgument);

        List<Pos_Product> paymentList = new List<Pos_Product>();
        foreach (GridViewRow gvr in gvPayment.Rows)
        {
            HiddenField hfSerial = (HiddenField)gvr.FindControl("hfSerial");
            HiddenField hfIssueFromID = (HiddenField)gvr.FindControl("hfIssueFromID");
            Label lblCardNo = (Label)gvr.FindControl("lblCardNo");
            Label lblCardType = (Label)gvr.FindControl("lblCardType");
            Label lblIssueFrom = (Label)gvr.FindControl("lblIssueFrom");
            Label lblAmount = (Label)gvr.FindControl("lblAmount");

            Pos_Product PaymentGrid = new Pos_Product();
            PaymentGrid.Pos_ProductID = int.Parse(hfSerial.Value);
            PaymentGrid.ExtraField1 = lblCardNo.Text;
            PaymentGrid.ExtraField2 = lblCardType.Text;
            PaymentGrid.ExtraField3 = lblIssueFrom.Text;
            PaymentGrid.ExtraField4 = hfIssueFromID.Value;
            PaymentGrid.ExtraField5 = lblAmount.Text;

            paymentList.Add(PaymentGrid);
        }

        
        int deleted_i = -1;
        for (int i = 0; i < paymentList.Count; i++)
        {
            if (id == paymentList[i].Pos_ProductID)
            {
                deleted_i = i;
                break;
            }
        }
        if (deleted_i != -1)
        {
            paymentList.Remove(paymentList[deleted_i]);
        }

        gvPayment.DataSource = paymentList;
        gvPayment.DataBind();

        decimal totalAmount = 0;
        foreach (GridViewRow gvr in gvPayment.Rows)
        {
            Label lblAmount = (Label)gvr.FindControl("lblAmount");
            totalAmount += decimal.Parse(lblAmount.Text);
        }

        txtCardAmount.Text = totalAmount.ToString("0,0.00");
        ((Label)gvPayment.FooterRow.FindControl("lblTotalCardAmountFooter")).Text = totalAmount.ToString("0,0.00");
        
        txtCashAmount_TextChanged(this, new EventArgs());   
        
    }

    protected void lbDeletePreviewGrid_Click(object sender, EventArgs e)
    {
        LinkButton linkButton = new LinkButton();
        linkButton = (LinkButton)sender;
        int id = Convert.ToInt32(linkButton.CommandArgument);

        List<Pos_Product> takenFromPreviewProduct = new List<Pos_Product>();

        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            Pos_Product prod = new Pos_Product();

            HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");

            Label lblProductName = (Label)gvr.FindControl("lblProductName");
            Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
            Label lblSizeName = (Label)gvr.FindControl("lblSizeName");
            Label lblColorName = (Label)gvr.FindControl("lblColorName");
            Label lblProductStatusName = (Label)gvr.FindControl("lblProductStatusName");
            Label lblStock = (Label)gvr.FindControl("lblStock");
            Label lblSalePrice = (Label)gvr.FindControl("lblSalePrice");
            Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");

            TextBox txtQty = (TextBox)gvr.FindControl("txtQty");
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");

            prod.Pos_ProductID = int.Parse(hfPos_ProductID.Value);
            prod.ProductName = lblProductName.Text;
            prod.BarCode = lblBarCode.Text;
            prod.ExtraField1 = txtQty.Text;
            prod.ExtraField10 = lblSizeName.Text;
            prod.ExtraField2 = lblColorName.Text;
            prod.ExtraField3 = lblProductStatusName.Text;
            prod.ExtraField4 = lblStock.Text;
            prod.ExtraField5 = lblSalePrice.Text;
            prod.ExtraField6 = (decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)).ToString("0,0.00");
            prod.ExtraField7 = "0";//not fund 
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text) != 0 ? (decimal.Parse(txtDiscountAmountGrid.Text)) : ((decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)) * (decimal.Parse(txtDiscountGrid.Text) / 100));
            prod.ExtraField8 = decimal.Parse(txtVatGrid.Text) == 0 ? "0.00" : ((decimal.Parse(prod.ExtraField6) - prod.DiscountAmount) * (decimal.Parse(txtVatGrid.Text) / 100)).ToString("0,0.00");
            prod.ExtraField9 = (decimal.Parse(prod.ExtraField6) - prod.DiscountAmount + decimal.Parse(prod.ExtraField8)).ToString("0,0.00");

            prod.AccesoriesCost = decimal.Parse(prod.ExtraField8);
            prod.FabricsCost = prod.DiscountAmount;

            //Rewrite
            prod.ExtraField8 = txtVatGrid.Text;
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text);
            prod.DiscountPercentage = decimal.Parse(txtDiscountGrid.Text);

            if (txtQty.Text != "0")
                takenFromPreviewProduct.Add(prod);
        }

        int deleted_i = -1;
        for (int i = 0; i < takenFromPreviewProduct.Count; i++)
        {
            if (id == takenFromPreviewProduct[i].Pos_ProductID)
            {
                deleted_i = i;
                break;
            }
        }
        if (deleted_i != -1)
        {
            takenFromPreviewProduct.Remove(takenFromPreviewProduct[deleted_i]);
        }

        gvPreview.DataSource = takenFromPreviewProduct;
        gvPreview.DataBind();

        decimal totalStock = 0;
        decimal qty = 0;
        decimal totalAmount = 0;
        decimal SubtotalAmount = 0;
        decimal discountSum = 0;
        decimal vatSum = 0;
        foreach (Pos_Product prod in takenFromPreviewProduct)
        {
            totalAmount += decimal.Parse(prod.ExtraField6);
            SubtotalAmount += decimal.Parse(prod.ExtraField9);
            totalStock += decimal.Parse(prod.ExtraField4);
            qty += decimal.Parse(prod.ExtraField1);
            vatSum += prod.AccesoriesCost;
            discountSum += prod.FabricsCost;
        }

        ((Label)gvPreview.FooterRow.FindControl("lblStockFooter")).Text = totalStock.ToString("0,0");
        ((Label)gvPreview.FooterRow.FindControl("lblStockSalePriceFooter")).Text = totalAmount.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblQtyFooter")).Text = qty.ToString("0,0");
        ((Label)gvPreview.FooterRow.FindControl("lblSubTotalSalePriceFooter")).Text = SubtotalAmount.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblDiscountAmountTotalFooter")).Text = discountSum.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblVatGridTotalFooter")).Text = vatSum.ToString("0,0.00");

        txtSubTotal.Text = totalAmount.ToString("0,0.00");
        txtVat.Text = vatSum.ToString("0,0.00");
        txtDiscount.Text = discountSum.ToString("0,0.00");
        
        lblTotalQty.Text = qty.ToString("0,0");

        txtCashAmount_TextChanged(this, new EventArgs());
    }

    private void recalculate()
    {
        List<Pos_Product> takenFromPreviewProduct = new List<Pos_Product>();

        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            Pos_Product prod = new Pos_Product();

            HiddenField hfPos_ProductID = (HiddenField)gvr.FindControl("hfPos_ProductID");

            Label lblProductName = (Label)gvr.FindControl("lblProductName");
            Label lblBarCode = (Label)gvr.FindControl("lblBarCode");
            Label lblSizeName = (Label)gvr.FindControl("lblSizeName");
            Label lblColorName = (Label)gvr.FindControl("lblColorName");
            Label lblProductStatusName = (Label)gvr.FindControl("lblProductStatusName");
            Label lblStock = (Label)gvr.FindControl("lblStock");
            Label lblSalePrice = (Label)gvr.FindControl("lblSalePrice");
            Label lblStockSalePrice = (Label)gvr.FindControl("lblStockSalePrice");

            TextBox txtQty = (TextBox)gvr.FindControl("txtQty");
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");

            if (decimal.Parse(lblStock.Text) < decimal.Parse(txtQty.Text))
            {
                showAlartMessage(lblBarCode.Text +" Stock is less than your given Quantity");
                continue;
            }


            prod.Pos_ProductID = int.Parse(hfPos_ProductID.Value);
            prod.ProductName = lblProductName.Text;
            prod.BarCode = lblBarCode.Text;
            prod.ExtraField1 = txtQty.Text;
            prod.ExtraField10 = lblSizeName.Text;
            prod.ExtraField2 = lblColorName.Text;
            prod.ExtraField3 = lblProductStatusName.Text;
            prod.ExtraField4 = lblStock.Text;
            prod.ExtraField5 = lblSalePrice.Text;
            prod.ExtraField6 = (decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)).ToString("0,0.00");
            prod.ExtraField7 = "0";//not fund 
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text) != 0 ? (decimal.Parse(txtDiscountAmountGrid.Text)) : ((decimal.Parse(lblSalePrice.Text) * decimal.Parse(txtQty.Text)) * (decimal.Parse(txtDiscountGrid.Text) / 100));
            prod.ExtraField8 = decimal.Parse(txtVatGrid.Text) == 0 ? "0.00" : ((decimal.Parse(prod.ExtraField6) - prod.DiscountAmount) * (decimal.Parse(txtVatGrid.Text) / 100)).ToString("0,0.00");
            prod.ExtraField9 = (decimal.Parse(prod.ExtraField6) - prod.DiscountAmount + decimal.Parse(prod.ExtraField8)).ToString("0,0.00");

            prod.AccesoriesCost = decimal.Parse(prod.ExtraField8);
            prod.FabricsCost = prod.DiscountAmount;

            //Rewrite
            prod.ExtraField8 = txtVatGrid.Text;
            prod.DiscountAmount = decimal.Parse(txtDiscountAmountGrid.Text);
            prod.DiscountPercentage = decimal.Parse(txtDiscountGrid.Text);

            if (txtQty.Text != "0")
                takenFromPreviewProduct.Add(prod);
        }


        gvPreview.DataSource = takenFromPreviewProduct;
        gvPreview.DataBind();

        decimal totalStock = 0;
        decimal qty = 0;
        decimal totalAmount = 0;
        decimal SubtotalAmount = 0;
        decimal discountSum = 0;
        decimal vatSum = 0;
        foreach (Pos_Product prod in takenFromPreviewProduct)
        {
            totalAmount += decimal.Parse(prod.ExtraField6);
            SubtotalAmount += decimal.Parse(prod.ExtraField9);
            totalStock += decimal.Parse(prod.ExtraField4);
            qty += decimal.Parse(prod.ExtraField1);
            vatSum += prod.AccesoriesCost;
            discountSum += prod.FabricsCost;
        }

        ((Label)gvPreview.FooterRow.FindControl("lblStockFooter")).Text = totalStock.ToString("0,0");
        ((Label)gvPreview.FooterRow.FindControl("lblStockSalePriceFooter")).Text = totalAmount.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblQtyFooter")).Text = qty.ToString("0,0");
        ((Label)gvPreview.FooterRow.FindControl("lblSubTotalSalePriceFooter")).Text = SubtotalAmount.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblDiscountAmountTotalFooter")).Text = discountSum.ToString("0,0.00");
        ((Label)gvPreview.FooterRow.FindControl("lblVatGridTotalFooter")).Text = vatSum.ToString("0,0.00");

        txtSubTotal.Text = totalAmount.ToString("0,0.00");
        txtVat.Text = vatSum.ToString("0,0.00");
        txtDiscount.Text = discountSum.ToString("0,0.00");
        

        lblTotalQty.Text = qty.ToString("0,0");

        txtCashAmount_TextChanged(this, new EventArgs());
    }

    protected void txtQty_TextChanged(object sender, EventArgs e)
    {
        recalculate();
    }

    protected void ddlPaymentMood_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentMood.SelectedValue == "Cash")
        {
            btnAddCardPayment.Enabled = false;
            txtCashAmount.Enabled = true;
            
        }
        else if (ddlPaymentMood.SelectedValue == "Credit")
        {
            btnAddCardPayment.Enabled = true;
            txtCashAmount.Enabled = false;
        
        }
        else if (ddlPaymentMood.SelectedValue == "Cash & Credit")
        {
            btnAddCardPayment.Enabled = true;
            txtCashAmount.Enabled = true;

        }
    }

    protected void txtCashAmount_TextChanged(object sender, EventArgs e)
    {
        if ((decimal.Parse(txtCashAmount.Text) + decimal.Parse(txtReturnAmount.Text) + decimal.Parse(txtCardAmount.Text) - decimal.Parse(txtPaidAmount.Text)) >= 0)
        {
            txtRefundOrDue.ForeColor = System.Drawing.Color.Green;
        }
        else
        {
            txtRefundOrDue.ForeColor = System.Drawing.Color.Red;
        }

        txtPayableAmount.Text = (decimal.Parse(txtSubTotal.Text) - decimal.Parse(txtDiscount.Text) + decimal.Parse(txtVat.Text)).ToString("0,0.00");
        txtPaidAmount.Text = txtPayableAmount.Text;

        txtRefundOrDue.Text = (decimal.Parse(txtCashAmount.Text) + decimal.Parse(txtReturnAmount.Text) + decimal.Parse(txtCardAmount.Text) - decimal.Parse(txtPaidAmount.Text)).ToString("0,0.00");
    }

    protected void btnApplyDiscount_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");

            HiddenField hfVatGrid = (HiddenField)gvr.FindControl("hfVatGrid");
            HiddenField hfDiscountGrid = (HiddenField)gvr.FindControl("hfDiscountGrid");
            HiddenField hfDiscountAmountGrid = (HiddenField)gvr.FindControl("hfDiscountAmountGrid");

            hfVatGrid.Value = txtVatGrid.Text;
            hfDiscountGrid.Value = txtDiscountGrid.Text;
            hfDiscountAmountGrid.Value = txtDiscountAmountGrid.Text;

            txtDiscountGrid.Text = txtDiscountPercentage.Text;
            txtDiscountAmountGrid.Text = "0.00";
        }

        recalculate();
    }
    protected void btnAuto_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvr in gvPreview.Rows)
        {
            TextBox txtVatGrid = (TextBox)gvr.FindControl("txtVatGrid");
            TextBox txtDiscountGrid = (TextBox)gvr.FindControl("txtDiscountGrid");
            TextBox txtDiscountAmountGrid = (TextBox)gvr.FindControl("txtDiscountAmountGrid");

            HiddenField hfVatGrid = (HiddenField)gvr.FindControl("hfVatGrid");
            HiddenField hfDiscountGrid = (HiddenField)gvr.FindControl("hfDiscountGrid");
            HiddenField hfDiscountAmountGrid = (HiddenField)gvr.FindControl("hfDiscountAmountGrid");

            txtVatGrid.Text=hfVatGrid.Value;
            txtDiscountGrid.Text=hfDiscountGrid.Value ;
            txtDiscountAmountGrid.Text=hfDiscountAmountGrid.Value;
        }

        recalculate();
    }
    protected void txtBarCode_TextChanged(object sender, EventArgs e)
    {
        txtBarCode.Text = txtBarCode.Text.Trim();
        btnSearch_Click(this, new EventArgs());
        if (txtBarCode.Text != "")
        {
            btnAddToPreview_Click(this, new EventArgs());
        }
    }
    protected void txtInvoiceNo_TextChanged(object sender, EventArgs e)
    {
        string sql = @"Select Pos_TransactionMasterID from Pos_TransactionMaster where TransactionID=" + txtInvoiceNo.Text + " and Pos_TransactionTypeID=13"
         +" and WorkSatationID=" + ddlWorkStationSearch.SelectedValue;
        DataSet ds = CommonManager.SQLExec(sql);
        if (ds.Tables[0].Rows.Count == 0)
        {
            showAlartMessage("Invalid Invoice # for this branch");
            return;
        }

        hfInvoiceNo.Value = ds.Tables[0].Rows[0][0].ToString();
        
        sql = @"
SELECT Pos_Transaction.Pos_TransactionID,
Pos_TransactionMaster.TransactionID,
Pos_TransactionMaster.ExtraField4 as CustomerMobileNo,
Pos_TransactionMaster.Pos_TransactionMasterID,
Pos_Product.StyleCode as Style,Pos_Product.BarCode
,Pos_Size.SizeName,Pos_Color.ColorName
,Pos_Product.ProductName,Pos_Product.Pos_ProductID
,(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) as [Stock]
,Pos_Product.SalePrice 
,((cast(Pos_Transaction.ExtraField1 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) as DiscountAmount
,((cast(Pos_Transaction.ExtraField2 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) as VatAmount
,(((Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) * Pos_Product.SalePrice) - ((cast(Pos_Transaction.ExtraField1 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) +((cast(Pos_Transaction.ExtraField2 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))))) as Total
      ,((Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) * Pos_Product.SalePrice) as StockSalePrice
,[VatPercentageAlways] =cast(ACC_ChartOfAccountLabel4.ExtraField3 as decimal(10,2))  
,[TotalCostPerProduct] =([Pos_Product].[FabricsCost] + [Pos_Product].[AccesoriesCost] + [Pos_Product].[Overhead]+[Pos_Product].[OthersCost]+[Pos_Product].[PurchasePrice])
      
FROM Pos_Product
  inner join ACC_ChartOfAccountLabel4 on Pos_Product.ProductID=ACC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID
  inner join Pos_Size on Pos_Product.Pos_SizeID=Pos_Size.Pos_SizeID
  inner join Pos_Color on Pos_Product.Pos_ColorID=Pos_Color.Pos_ColorID
inner join Pos_Transaction on Pos_Transaction.Pos_ProductID =Pos_Product.Pos_ProductID
inner join Pos_TransactionMaster on Pos_TransactionMaster.Pos_TransactionMasterID = Pos_Transaction.Pos_ProductTransactionMasterID
 where   Pos_TransactionMaster.Pos_TransactionMasterID =" + ds.Tables[0].Rows[0][0].ToString() + @"
--and  Pos_Transaction.Quantity > cast(Pos_Transaction.ExtraField4  as decimal(10,2))
and  Pos_Transaction.ExtraField4='0'
order by Pos_Product.StyleCode,Pos_Product.BarCode
";

        ds = CommonManager.SQLExec(sql);
        gvReturnInvoice.DataSource = CommonManager.SQLExec(sql).Tables[0];
        gvReturnInvoice.DataBind();

        decimal soldQty = 0;
        decimal salePrice = 0;
        decimal vat = 0;
        decimal discount = 0;
        decimal total = 0;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            soldQty += decimal.Parse(dr["Stock"].ToString());
            salePrice += decimal.Parse(dr["StockSalePrice"].ToString());
            vat += decimal.Parse(dr["VatAmount"].ToString());
            discount += decimal.Parse(dr["DiscountAmount"].ToString());
            total += decimal.Parse(dr["Total"].ToString());
        }
        try
        {
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblSoldQtyFooter")).Text = soldQty.ToString("0");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblStockSalePriceFooter")).Text = salePrice.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblVatFooter")).Text = vat.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblDiscountFooter")).Text = discount.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblTotalFooter")).Text = total.ToString("0,0.00");
        }
        catch (Exception ex)
        { }
    }

    protected void btnClearReturn_Click(object sender, EventArgs e)
    {
        txtBarCodeSalesReturn.Text = "";
        txtInvoiceNo.Text = "";
        loadReturnGrid("''");
    }

    protected void txtBarCodeSalesReturn_TextChanged(object sender, EventArgs e)
    {
        if (txtBarCodeSalesReturn.Text == "")
        {
            return;
        }

        if (!hfBarcodeReturn.Value.Contains("'" + txtBarCodeSalesReturn.Text + "'"))
        {
            hfBarcodeReturn.Value += (hfBarcodeReturn.Value == "" ? "" : ",") + "'" + txtBarCodeSalesReturn.Text + "'";
        }

        loadReturnGrid(hfBarcodeReturn.Value);
    }

    private void loadReturnGrid(string barcode)
    {

        string sql = @"
            SELECT Pos_Transaction.Pos_TransactionID,
Pos_TransactionMaster.TransactionID,
Pos_TransactionMaster.ExtraField4 as CustomerMobileNo,
Pos_TransactionMaster.Pos_TransactionMasterID,
            Pos_Product.StyleCode as Style,Pos_Product.BarCode
            ,Pos_Size.SizeName,Pos_Color.ColorName
            ,Pos_Product.ProductName,Pos_Product.Pos_ProductID
           ,(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) as [Stock]
,Pos_Product.SalePrice 
,((cast(Pos_Transaction.ExtraField1 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) as DiscountAmount
,((cast(Pos_Transaction.ExtraField2 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) as VatAmount
,(((Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) * Pos_Product.SalePrice) - ((cast(Pos_Transaction.ExtraField1 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2)))) +((cast(Pos_Transaction.ExtraField2 as decimal(10,2))/Pos_Transaction.Quantity)*(Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))))) as Total
      ,((Pos_Transaction.Quantity - cast(Pos_Transaction.ExtraField4  as decimal(10,2))) * Pos_Product.SalePrice) as StockSalePrice
,[VatPercentageAlways] =cast(ACC_ChartOfAccountLabel4.ExtraField3 as decimal(10,2))  
,[TotalCostPerProduct] =([Pos_Product].[FabricsCost] + [Pos_Product].[AccesoriesCost] + [Pos_Product].[Overhead]+[Pos_Product].[OthersCost]+[Pos_Product].[PurchasePrice])
         FROM Pos_Product
           inner join ACC_ChartOfAccountLabel4 on Pos_Product.ProductID=ACC_ChartOfAccountLabel4.ACC_ChartOfAccountLabel4ID
     inner join Pos_Size on Pos_Product.Pos_SizeID=Pos_Size.Pos_SizeID
              inner join Pos_Color on Pos_Product.Pos_ColorID=Pos_Color.Pos_ColorID
            inner join Pos_Transaction on Pos_Transaction.Pos_ProductID =Pos_Product.Pos_ProductID
            inner join Pos_TransactionMaster on Pos_TransactionMaster.Pos_TransactionMasterID = Pos_Transaction.Pos_ProductTransactionMasterID
             where Pos_Product.BarCode in (" + barcode + @") and Pos_TransactionMaster.Pos_TransactionTypeID=13 and Pos_TransactionMaster.WorkSatationID =" + ddlWorkStationSearch.SelectedValue + @"
--and  Pos_Transaction.Quantity > cast(Pos_Transaction.ExtraField4  as decimal(10,2))
and  Pos_Transaction.ExtraField4='0'
order by Pos_Product.StyleCode,Pos_Product.BarCode
            ";

        DataSet ds = CommonManager.SQLExec(sql);
        gvReturnInvoice.DataSource = CommonManager.SQLExec(sql).Tables[0];
        gvReturnInvoice.DataBind();

        decimal soldQty = 0;
        decimal salePrice = 0;
        decimal vat = 0;
        decimal discount = 0;
        decimal total = 0;
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            soldQty += decimal.Parse(dr["Stock"].ToString());
            salePrice += decimal.Parse(dr["StockSalePrice"].ToString());
            vat += decimal.Parse(dr["VatAmount"].ToString());
            discount += decimal.Parse(dr["DiscountAmount"].ToString());
            total += decimal.Parse(dr["Total"].ToString());
        }

        foreach (GridViewRow gvr in gvReturnInvoice.Rows)
        {
            TextBox txtRtnQty = (TextBox)gvr.FindControl("txtRtnQty");

            txtRtnQty.Text = "1";
        }
        //txtRtnQty
        try
        {
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblSoldQtyFooter")).Text = soldQty.ToString("0");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblStockSalePriceFooter")).Text = salePrice.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblVatFooter")).Text = vat.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblDiscountFooter")).Text = discount.ToString("0,0.00");
            ((Label)gvReturnInvoice.FooterRow.FindControl("lblTotalFooter")).Text = total.ToString("0,0.00");
        }
        catch (Exception ex)
        { }
    }

    protected void btnProcessReturn_Click(object sender, EventArgs e)
    {
        //Process return transaction master and transaction
        //increatse the qty in showroom
        //Journla process
        
        decimal totalReturnAmount = 0;
        
        foreach (GridViewRow gvr in gvReturnInvoice.Rows)
        {
            TextBox txtRtnQty = (TextBox)gvr.FindControl("txtRtnQty");
            Label lblSoldQty = (Label)gvr.FindControl("lblSoldQty");
            
            
            if (txtRtnQty.Text != "0" && txtRtnQty.Text != "")
            {
                Label lblTotal = (Label)gvr.FindControl("lblTotal");
                totalReturnAmount += ((decimal.Parse(lblTotal.Text) / decimal.Parse(lblSoldQty.Text)) * decimal.Parse(txtRtnQty.Text));
                txtRtnQty.Enabled = false;
            }
        }

        txtReturnAmount.Text = totalReturnAmount.ToString("0,0.00");
        txtCashAmount_TextChanged(this, new EventArgs());
    }
    
}
